<template>
    <view class="pub_page pub_page_bg pub_chat pub_header_padding pub_tabbar_padding">
        <pub-tabbar :active="0" :adSrc="adSrc"></pub-tabbar>
        <pub-head headerName="chat_index" :headerConfig="headerConfig" @headerBack="headerBack"></pub-head>
        <pub-dialog dialogName="chat_index" v-show="dialogShow" @dialogBack="dialogBack"
            :dialogConfig="dialogConfig"></pub-dialog>
        <div class="pub_page_scroll page_box">
            <div class="lis_div">
                <div class="banner_div" v-if="bannerList.length">
                    <swiper class="swiper" circular :indicator-dots="true" :autoplay="true" :interval="5000"
                        v-cloak:indicator-dots="false">
                        <swiper-item v-for="(item, key) in bannerList" :key="key">
                            <view class="swiper_item" :style="{ backgroundImage: 'url(' + item + ')' }"></view>
                        </swiper-item>
                    </swiper>
                </div>

                <uni-swipe-action ref="swipeAction">
                    <uni-swipe-action-item v-for="(li, key) in conversationList" :key="key">
                        <chatList @openChatInfo="openChatInfo(li,key)" :chatInfo="li"
                            :friendInfoData="friendInfoData" />
                        <template v-slot:right>
                            <view class="del" @click="deleteChat(li,key)">
                                <text class="icon icon-font-basic icon-b-delete-1"></text>
                            </view>
                        </template>
                    </uni-swipe-action-item>
                </uni-swipe-action>
            </div>
            <!-- <z-paging ref="Zpaging" class="lis_div" @query="getConversationList" v-model="conversationList"
                :show-loading-more-no-more-view="false" :refresher-enabled="false" :fixed="false"
                :auto-clean-list-when-reload="false">
            </z-paging> -->
        </div>
        <div class="user_alert_div" v-if="userAlertShow">
            <div class="user_box" :class="userAlertShow ? 'user_box_animation' : ''">
                <div class="icon_div">
                    <pub-image class="img_1" :src="'../../static/aimg/img_1.png'"
                        @imgClick="closeUserAlert()"></pub-image>
                    <pub-image v-if="mType==1&&letterHasList.length>0&&!isCreateGroup" @imgClick="isCreateGroup=true"
                        class="img_3" :src="'../../static/aimg/img_8.png'"></pub-image>
                    <div class="tbtns" v-if="isCreateGroup">
                        <div class="tbtn" @click="closeCreatGroup()">取消</div>
                        <div class="tbtn" @click="toCreatGroup()">确定</div>
                    </div>
                    <!-- <pub-image class="img_2" v-if="!isCreateGroup" :src="'../../static/aimg/img_7.png'"
                        @imgClick="userAlertShow=false;$comFun.openWin('/pages/chat/add')"></pub-image> -->
                </div>
                <div class="tab_div" :class="isCreateGroup?'tab_div_none':''">
                    <div class="tab" :class="mType==1?'tab_active':''" @click="mTypeClick(1)">联系人</div>
                    <div class="tab" :class="mType==2?'tab_active':''" @click="mTypeClick(2)">群组</div>
                </div>
                <scroll-view v-if="mType==1" :scroll-top="friendDivScrollTop" scroll-y="true" class="lis_div"
                    id="friendDiv">
                    <div class="lis" v-for="(li, key) in friendList" :key="key">
                        <div class="li_title" :id="`letter_title_${key=='#'?'other':key}`" v-if="li.length">{{ key }}
                        </div>
                        <div class="li" :class="isCreateGroup?'li_group':''" v-for="(cli, ckey) in li" :key="ckey"
                            @click="friendClick(cli,ckey)">
                            <div class="choose" v-if="isCreateGroup">
                                <span class="choose icon-font-basic"
                                    :class="groupMemberList.indexOf(cli.userId) != -1 ? 'icon-b-select-6' : 'icon-b-select-4'"></span>
                            </div>
                            <pub-image class="img" :src="cli.userAvatar"></pub-image>
                            <div class="text">
                                <div class="span_1" v-if="cli.role==1"></div>
                                <div class="span_2" :class="cli.role==1?'span_2_red':''">{{
                                    cli.userName }}
                                </div>
                                <!-- <div class="span_3" v-if="cli.level!=0">Lv.{{ cli.level }}</div> -->
                            </div>
                        </div>
                    </div>
                    <div v-if="letterHasList.length==0" class="pub_nodata_2"><br>暂无好友</div>
                </scroll-view>
                <div class="letter_div" v-if="mType==1">
                    <div class="li" v-for="(li, key) in letterHasList" :key="key"
                        :class="li == letterVal ? 'li_active' : ''" @click="letterClick(li)">{{ li }}</div>
                </div>

                <div class="lis_div" v-if="mType==2">
                    <div class="lis" v-for="(li, key) in groupList" :key="key">
                        <div class="li" @click="groupClick(li,key)">
                            <pub-image class="img" :src="li.groupAvatar"></pub-image>
                            <div class="text">
                                <div class="name">{{ li.groupName }}</div>
                            </div>
                        </div>
                    </div>
                    <div v-if="groupList.length==0" class="pub_nodata_2"><br>暂无群聊</div>
                </div>
            </div>
            <div class="user_box_mask" @click="closeUserAlert()"></div>
        </div>
        <div class="group_create_alert_div" v-if="isCreateGroupAlert">
            <div class="alert_box">
                <pub-image class="logo" :src="'../../static/logo.png'" mode="widthFix" />
                <div class="title">创建群聊</div>
                <div class="pub_inputs">
                    <div class="abox">
                        <div class="ali ali_align_right">
                            <div class="atitle">群名</div>
                            <input class="ainput" type="text" placeholder="请输入" maxlength="15" v-model="groupName">
                        </div>
                    </div>
                </div>
                <div class="msg">*注：创建群聊需支付 {{ createGroupPrice }} 金币</div>
                <div class="pub_btn" @click="sureCreatGroup">确定创建</div>
            </div>
            <text class="close icon-font-basic icon-b-off" @click="isCreateGroupAlert=false"></text>
        </div>
    </view>
</template>

<script>
import vPinyin from '@/common/js/pinyin'

import chatList from '@/pages/chat/components/chat-list.vue'
export default {
    components: { chatList },
    data() {
        return {
            headerConfig: {
                title: '会话',//标题栏内容
                left_type: 2,
                left_content: '../../static/aimg/img_1.png',
                right_type: 2,//右侧区域类型  0不出现  1文字  2图片
                right_content: '../../static/aimg/img_122.png',//右侧内容  right_type为1时文字内容 为2时图片链接
            },
            dialogShow: false,
            dialogConfig: {
                title: '提示',//标题栏内容
                content: ''
            },

            bannerList: [],
            adSrc: '',

            userInfo: '',
            locationInfo: '',

            letterList: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '#'],
            letterVal: '',
            letterHasList: [],
            userAlertShow: false,

            friendDivScrollTop: 0,
            friendList: {},
            friendInfoData: {},
            groupList: [],

            mType: 1,//1联系人  2群组
            createGroupPrice: 0,//创建群聊价格
            isCreateGroup: false,//是否在创建群组
            isCreateGroupAlert: false,//是否在创建群组-alert
            groupMemberList: [],//创建群聊时所选择的用户id
            groupName: '',

            conversationList: [],//会话列表
            conversationLoad: false,
        };
    },
    onLoad() {
        this.initPageInfo();

        this.getUserInfo();
        this.getBanner();
        this.getPopAd();
        this.getConfig();
        // #ifdef APP-PLUS
        if (process.env.NODE_ENV == 'production') {
            this.initAppUpdate();
        }
        // #endif
    },
    onHide() { },
    onShow() {
        if (this.conversationLoad) {
            this.getConversationList();
            // this.$refs.Zpaging.reload();
        }
    },
    methods: {
        dialogBack(data) {
            // console.log(data);
            // if (data.name == 'chat_index') {
            //     if (data.key == 1) {
            //         this.$permision.gotoAppPermissionSetting();
            //     } else if (data.key == 0) {
            //         this.dialogShow = false;
            //         this.getUserLocation();
            //     }
            // }
        },
        headerBack(data) {
            if (data.type == 'left') {
                this.userAlertShow = true;
                if (this.$txChat) {
                    this.getFriendList();
                    this.getGroupList();
                }
            } else if (data.type == 'right') {
                this.$comFun.openWin('/pages/chat/add');
            }
        },
        async getConfig() {
            let configRes = await getApp().getConfigList();
            // console.log(configRes);
            this.createGroupPrice = configRes.createGroupPrice;
        },
        async getPopAd() {
            const res = await this.$request.get('public/getAd', {
                key: 'open-ad'
            });
            // console.log(res);
            if (res.code == 200) {
                this.adSrc = res.result.length > 0 && res.result[0].image ? res.result[0].image : '';
            }
        },
        onConversationListUpdated(event) {
            const that = this;
            console.log("chat-onConversationListUpdated", event.data); // 包含 Conversation 实例的数组
            if (event && event.data) {
                let conversationList = (event?.data || []).filter(li => {
                    return li.conversationID != "@TIM#SYSTEM"
                });
                that.conversationList = conversationList;
            }
        },
        initPageInfo() {
            const that = this;
            getApp().initChat(async (res) => {
                if (res) {
                    // 更新当前用户信息
                    // allowType=>当被人加好友时
                    // TencentCloudChat.TYPES.ALLOW_TYPE_ALLOW_ANY（允许直接加为好友）
                    // TencentCloudChat.TYPES.ALLOW_TYPE_NEED_CONFIRM（需要验证）
                    // TencentCloudChat.TYPES.ALLOW_TYPE_DENY_ANY（拒绝）
                    // const userInfo = that.$comFun.getUserInfo();
                    // let gender = {
                    //     2: that.$TencentCloudChat.TYPES.GENDER_FEMALE,
                    //     1: that.$TencentCloudChat.TYPES.GENDER_MALE,
                    //     0: that.$TencentCloudChat.TYPES.GENDER_UNKNOWN,
                    // }
                    // let promise_1 = that.$txChat.updateMyProfile({
                    //     nick: userInfo.nickName,
                    //     avatar: userInfo.avatar,
                    //     gender: gender[userInfo.sex],
                    //     allowType: that.$TencentCloudChat.TYPES.ALLOW_TYPE_ALLOW_ANY
                    // })
                    // promise_1.then(function (imResponse) {
                    //     console.log('chat-updateMyProfile', imResponse.data); // 更新资料成功
                    // }).catch(function (imError) {
                    //     console.warn('chat-updateMyProfile error:', imError); // 更新资料失败的相关信息
                    // });

                    // setTimeout(() => {
                    //     that.$refs.Zpaging.reload();
                    // }, 400)

                    // that.getConversationList();

                    that.conversationLoad = true;

                    that.$txChat.off(that.$TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED, that.onConversationListUpdated);

                    setTimeout(() => {
                        // 监听会话列表
                        that.$txChat.on(that.$TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED, that.onConversationListUpdated);
                    }, 100)
                    setTimeout(() => {
                        that.getFriendList();
                    }, 500)

                    uni.$on("chatConversationListUpdate", (res) => {
                        let findIndex = -1;
                        if (res.chatType == 1) {
                            findIndex = that.conversationList.findIndex(li => {
                                return li.conversationID == `C2C${res.userId}`
                            })
                        } else if (res.chatType == 2) {
                            findIndex = that.conversationList.findIndex(li => {
                                return li.conversationID == `GROUP${res.groupId}`
                            })
                        }
                        if (findIndex != -1) {
                            that.deleteChat(that.conversationList[findIndex], findIndex);
                        }
                    })
                }
            });
        },
        // 获取会话列表
        async getConversationList(pageNo, pageSize) {
            const that = this;
            // 获取全量的会话列表
            let promise = that.$txChat.getConversationList();
            promise.then(function (imResponse) {
                console.log('chat-getConversationList', imResponse);
                // 全量的会话列表，用该列表覆盖原有的会话列表
                let conversationList = (imResponse?.data?.conversationList || []).filter(li => {
                    return li.conversationID != "@TIM#SYSTEM"
                });
                that.conversationList = conversationList;
                // that.$refs.Zpaging.complete(conversationList);

            }).catch(function (imError) {
                that.conversationList = [];
                // 获取会话列表失败的相关信息
                // that.$refs.Zpaging.complete([]);
            });
        },
        // 获取好友列表
        async getFriendList() {
            const that = this;
            let friendList = {};
            that.letterList.forEach(li => {
                friendList[li] = [];
            })
            let friendInfoData = {};
            let promise = that.$txChat.getFriendList();
            promise.then(function (imResponse) {
                const fList = imResponse.data; // 好友列表
                console.log("chat-getFriendList", fList);
                that.friendDivScrollTop = 0;
                that.letterHasList = [];

                let letterHasList = [];
                fList.forEach(li => {
                    let namePinyin = vPinyin.chineseToPinYin(li.profile.nick.charAt(0)) || '#';
                    // console.log("namePinyin", namePinyin);
                    let letter = namePinyin[0].toUpperCase();
                    if (that.letterList.indexOf(letter) == -1) {
                        letter = '#';
                    }
                    // console.log("letter", letter);
                    let index = letterHasList.indexOf(letter);
                    if (index == -1) letterHasList.push(letter);
                    friendInfoData[li.profile.userID] = {
                        role: li.profile.role,
                        level: li.profile.level,
                    };
                    friendList[letter].push({
                        userName: li.profile.nick,
                        userAvatar: li.profile.avatar,
                        userId: li.profile.userID,
                        role: li.profile.role,
                        level: li.profile.level,
                    })
                });
                that.letterList.forEach(li => {
                    if (letterHasList.indexOf(li) != -1) {
                        that.letterHasList.push(li);
                    }
                })
                that.letterVal = that.letterHasList.length > 0 ? that.letterHasList[0] : '';
                that.$set(that, 'friendList', friendList);
                that.$set(that, 'friendInfoData', friendInfoData);
            }).catch(function (imError) {
                console.warn('getFriendList error:', imError); // 获取好友列表失败的相关信息
            });
        },
        async getGroupList() {
            const that = this;
            let promise = that.$txChat.getGroupList();
            promise.then(function (imResponse) {
                console.log("chat-getGroupList", imResponse.data.groupList); // 群组列表
                let groupList = imResponse?.data?.groupList || [];
                that.groupList = groupList.map(li => {
                    return {
                        groupName: li.name,
                        groupAvatar: li.avatar,
                        groupId: li.groupID,
                    }
                })
            }).catch(function (imError) {
                console.warn('getGroupList error:', imError); // 获取群组列表失败的相关信息
            });
        },
        openChatInfo(info, key) {
            if (info.type == 'C2C') {
                this.$comFun.openWin('/pages/chat/info', {
                    chatType: 1,
                    chatUserInfo: JSON.stringify({
                        userName: info.userProfile.nick,
                        userAvatar: info.userProfile.avatar,
                        userId: info.userProfile.userID,
                    })
                });
            } else if (info.type == 'GROUP') {
                this.$comFun.openWin('/pages/chat/info', {
                    chatType: 2,
                    chatGroupInfo: JSON.stringify({
                        groupName: info.groupProfile.name,
                        groupId: info.groupProfile.groupID,
                        groupAvatar: info.groupProfile.avatar,
                    })
                });
            }

        },
        closeUserAlert() {
            this.userAlertShow = false;
            this.isCreateGroup = false;
            this.groupMemberList = [];
        },
        letterClick(info) {
            const that = this;
            that.letterVal = info;
            const query = uni.createSelectorQuery().in(that);
            query.select("#friendDiv").fields({ rect: true, scrollOffset: true }).select(`#letter_title_${info == '#' ? 'other' : info}`).boundingClientRect().exec((l_data) => {
                // console.log("得到布局位置信息" + JSON.stringify(data));
                // console.log(l_data);
                let scrollTop = Math.abs(l_data[1].top + l_data[0].scrollTop - l_data[0].top);
                // console.log("scrollTop", scrollTop);
                that.friendDivScrollTop = scrollTop;
            });
        },
        mTypeClick(mType) {
            if (!this.isCreateGroup) {
                this.mType = mType;
            }
        },
        friendClick(info, key) {
            if (this.isCreateGroup) {
                let index = this.groupMemberList.indexOf(info.userId);
                if (index == -1) {
                    this.groupMemberList.push(info.userId);
                } else {
                    this.groupMemberList.splice(index, 1);
                }
            } else {
                this.userAlertShow = false;
                this.$comFun.openWin('/pages/chat/info', {
                    chatType: 1,
                    chatUserInfo: JSON.stringify({
                        ...info,
                    }),
                })
            }
        },
        groupClick(info, key) {
            this.userAlertShow = false;
            this.$comFun.openWin('/pages/chat/info', {
                chatType: 2,
                chatGroupInfo: JSON.stringify({
                    groupName: info.groupName,
                    groupId: info.groupId,
                    groupAvatar: info.groupAvatar,
                })
            })
        },
        closeCreatGroup() {
            this.isCreateGroup = false;
            this.groupMemberList = [];
        },
        async toCreatGroup() {
            const that = this;
            if (that.groupMemberList.length < 2) {
                that.$comFun.toast('请至少选择2个好友');
                return;
            }
            that.groupName = '';
            that.isCreateGroupAlert = true;
        },
        async sureCreatGroup() {
            const that = this;
            if (!that.groupName) {
                that.$comFun.toast('请填写群名称');
                return;
            }
            that.isCreateGroupAlert = false;
            let userIdList = that.groupMemberList.map(li => {
                return li
            })
            that.$comFun.openLoading();
            const res = await that.$request.post('chat/createGroup', {
                userIds: userIdList,
                groupName: that.groupName
            });
            console.log(1, res);
            if (res.code == 200) {
                const groupInfo = {
                    groupName: res.result.groupName,
                    groupId: res.result.groupNumber,
                    groupAvatar: res.result.groupAvatar,
                }
                that.$comFun.closeLoading();

                that.closeUserAlert();
                that.$comFun.openWin('/pages/chat/info', {
                    chatType: 2,
                    chatGroupInfo: JSON.stringify({
                        groupName: groupInfo.groupName,
                        groupId: groupInfo.groupId,
                        groupAvatar: groupInfo.groupAvatar,
                    })
                });
            } else {
                that.$comFun.closeLoading();
                that.$comFun.toast(res.message || "失败，请稍后再试");
            }
        },
        deleteChat(info, key) {
            const that = this;
            // 删除单一会话, 并清空会话历史消息
            if (info) {
                console.log('chat-1', info, key);
                let promise = that.$txChat.deleteConversation(info.conversationID);
                promise.then(function (imResponse) {
                    // 删除会话成功
                    // that.conversationList.splice(key, 1);
                }).catch(function (imError) {
                    console.warn('deleteConversation error:', imError); // 删除会话失败的相关信息
                    that.$comFun.toast('失败，请稍后再试');
                });
            }
        },
        async getBanner() {
            const res = await this.$request.get('public/getAd', {
                key: 'index-ad'
            });
            // console.log(res);
            if (res.code == 200 && res.result.length > 0) {
                this.bannerList = res.result[0]?.image.split(",") || [];
            }
        },
        async getUserInfo() {
            const res = await this.$request.get('user/userInfo', {});
            // console.log(res);
            if (res.code == 200) {
                this.userInfo = res.result;
                if (!this.userInfo.province) {
                    // #ifdef APP-PLUS
                    this.getUserLocation();
                    // #endif
                    // #ifdef H5
                    this.locationInfo = {
                        latitude: 30.513494,
                        longitude: 104.060066,
                        address_txt: '四川省 成都市 双流区',
                        address: {
                            country: "中国",
                            province: "四川省",
                            city: "成都市",
                            district: "双流区",
                            street: "安公路",
                            streetNum: "3段-422",
                            cityCode: "75"
                        },
                    }
                    // this.saveUserLocation();
                    // #endif
                }
            }
        },
        async getUserLocation() {
            const that = this;
            // result 1=>已获取授权  0=>未获取授权-1=>被永久拒绝授权
            const result = await this.$permision.requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION');
            console.log("result:", result);
            if (result == 1) {
                uni.getLocation({
                    type: 'gcj02',
                    geocode: true,
                    success: function (res) {
                        console.log(res);
                        that.locationInfo = {
                            latitude: res.latitude,
                            longitude: res.longitude,
                            address_txt: `${res.address.province} ${res.address.city} ${res.address.district}`,
                            address: res.address,
                        };
                        that.saveUserLocation();
                    }
                });
            } else {
                // this.dialogConfig = {
                //     title: '提示',//标题栏内容
                //     content: '请先获取定位信息再进入APP',
                //     btn_list: [{
                //         txt: '已设置',
                //         color: '#555',
                //         bg_1: '#e8e8e8',
                //         bg_2: '#eee',
                //     }, {
                //         txt: '去设置权限',
                //         color: '#fff',
                //         bg_1: '#31A5FF',
                //         bg_2: '#0974FF'
                //     }]
                // };
                // this.dialogShow = true;
            }
        },
        async saveUserLocation() {
            uni.setStorageSync('userLocationInfo', this.locationInfo);
            const res = await this.$request.post('user/bindPosition', {
                lat: this.locationInfo.latitude,
                lon: this.locationInfo.longitude,
            });
            console.log(res);
        },
        async initAppUpdate() {
            const that = this;
            const res = await this.$request.get('public/getAppVersion', {});
            // console.log(res);
            // console.log(plus.runtime);
            // console.log(process.env.NODE_ENV);
            if (res.code == 200) {
                plus.runtime.getProperty(plus.runtime.appid, function (wgtinfo) {
                    // console.log(wgtinfo.versionCode);
                    const versionCode = wgtinfo.versionCode;
                    // const versionCode = 100;
                    // this.runtime = plus.runtime.versionCode + ',' + res.result.versionCode + ',' + (Number(res.result.versionCode) > Number(versionCode));
                    // console.log(this.runtime);
                    if (Number(res.result.versionCode) > Number(versionCode)) {
                        if (that.$store.state.deviceType == 'android') {
                            that.$store.dispatch('setAppUpdate', res.result.update_android_url)
                        } else if (that.$store.state.deviceType == 'ios') {
                            that.$store.dispatch('setAppUpdate', res.result.ios_url)
                        }
                    } else {
                        that.$store.dispatch('setAppUpdate', false)
                    }
                });
            }
        },
    },
};
</script>

<style lang="scss" scoped>
@import "@/common/css/chat.scss";
@import "@/pages/chat/emote/emote.scss";
</style>
